#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
    int sock_descriptor, port_number, n;
    struct sockaddr_in server_addr;
    struct hostent *server;

    char buffer[256];
    if (argc < 3) {
       fprintf(stderr,"modo de uso: %s hostname port\n", argv[0]);
       exit(0);
    }
    port_number = atoi(argv[2]);
    
    sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);
    
    if (sock_descriptor < 0){
        error("fallo al abrir el socket");
	}
	
	// meto en el struct el host
    server = gethostbyname(argv[1]);
    
    if (server == NULL) {
        fprintf(stderr,"no existe el host\n");
        exit(0);
    }
    
    // inicializo a cero el struct
    bzero((char *) &server_addr, sizeof(server_addr));
    
    
    server_addr.sin_family = AF_INET;
    
    bcopy((char *)server->h_addr, (char *)&server_addr.sin_addr.s_addr, server->h_length);
    
    server_addr.sin_port = htons(port_number);
    
    if (connect(sock_descriptor,(struct sockaddr *) &server_addr,sizeof(server_addr)) < 0){
        error("error al conectarse");
	}
	
    printf("Ingrese un mensaje: ");
    
    bzero(buffer,256);
    
    // leo desde standar input el msg
    fgets(buffer,255,stdin);
    // escribo en el socket el msg
    n = write(sock_descriptor, buffer, strlen(buffer));
    
    if (n < 0){
         error("fallo al escribir el socket");
	}
	
    bzero(buffer,256);
    
    n = read(sock_descriptor, buffer, 255);
    
    if (n < 0){
         error("fallo al leer desde el socket");
	}
	
    printf("%s\n", buffer);
    close(sock_descriptor);
    return 0;
}
